<!-- CREATE 2022-08-15 -->
<!-- AUTHOR 伊玖OneNine -->

<script setup lang="ts">
import type { UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui'
import type { FaceSearch } from '~/api/face/faceType'

const message = useMessage()

const faceImg = ref('')
// const modalLoading = ref(false)
const searchList = ref<FaceSearch[]>()
const fileListRef = ref<UploadFileInfo[]>([])

function fileRemove() {
  searchList.value = []
  faceImg.value = ''
}

// 自定义上传
async function customRequest({ file, onFinish, onError }: UploadCustomRequestOptions) {
  const image = file.file as File
  if ((image.type !== 'image/png') && (image.type !== 'image/jpeg')) {
    message.error('上传失败')
    onError()
  }

  const reander = new FileReader()
  reander.readAsDataURL(image)
  reander.onload = async () => {
    const res = reander.result!.toString()
    faceImg.value = res
    const { code, data } = await SearchFaceImage({ image: res })
    if (code === OK_CODE)
      searchList.value = data
    onFinish()
  }
}
</script>

<template>
  <n-card title="静态图片搜索" size="huge">
    <n-grid cols="16">
      <n-gi span="3">
        <n-card title="上传的图片">
          <n-upload
            v-model:file-list="fileListRef"
            accept="image/png, image/jpeg"
            list-type="image-card"
            :max="1"
            :custom-request="customRequest"
            :on-remove="fileRemove"
          />
        </n-card>
      </n-gi>
      <n-gi span="13">
        <n-card title="搜索到的列表">
          <n-table>
            <thead>
              <tr>
                <th>序号</th>
                <th>头像</th>
                <th>姓名</th>
                <th>学号</th>
                <th>相似度</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) of searchList" :key="item.id">
                <td>{{ index + 1 }}</td>
                <td>
                  <n-image width="100" height="100" lazy :src="item.image">
                    <template #placeholder>
                      <div class="image-loading">
                        加载中
                      </div>
                    </template>
                  </n-image>
                </td>
                <td>{{ item.name }}</td>
                <td>{{ item.studentId }}</td>
                <td>{{ item.compare }}</td>
              </tr>
            </tbody>
          </n-table>
        </n-card>
      </n-gi>
    </n-grid>
  </n-card>
</template>

<style scoped>
.image-loading {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #0001;
}
</style>
